//
//  OpenMailMessage.m
//  SulitLoan
//
//  Created by 虞嘉伟 on 2025/3/12.
//  
  

#import "OpenMailMessage.h"

@implementation OpenMailMessage

- (NSString *)name {
    return @"icePapaya";
}
- (instancetype)initWithController:(UIViewController *)controller {
    if (self = [super init]) {
        self.controller = controller;
    }
    return self;
}

- (void)handleMessage:(WKScriptMessage *)message {
    if ([message.name isEqualToString:self.name]) {
        NSDictionary *infoDictionary = NSBundle.mainBundle.infoDictionary;
        NSString *recipient = message.body;
        if ([recipient containsString:@"email:"]) {
            recipient = [recipient substringFromIndex:[recipient rangeOfString:@"email:"].length];
        }
        NSString *subject = @"";
        NSString *appName = infoDictionary[@"CFBundleDisplayName"] ?: infoDictionary[@"CFBundleName"];
        NSString *body = [NSString stringWithFormat:@"APP:%@\nPhone: %@\nI need help", appName, User.user.phone];

        // 构造 mailto URL
        NSString *mailtoURLString = [NSString stringWithFormat:@"mailto:%@?subject=%@&body=%@",
                                     recipient,
                                     [subject stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]],
                                     [body stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]]];

        NSURL *mailtoURL = [NSURL URLWithString:mailtoURLString];

        // 跳转到邮件应用
        if ([[UIApplication sharedApplication] canOpenURL:mailtoURL]) {
            [[UIApplication sharedApplication] openURL:mailtoURL options:@{} completionHandler:nil];
        } else {
            NSLog(@"无法打开邮件应用");
        }
    }
}

@end
